package longcaisuyun.longcai.com.yiliubabalongcaisuyun;


import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import android.widget.RemoteViews;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import net.tsz.afinal.http.HttpHandler;

import java.io.File;



/**
 *
 * @author hao
 * 服务
 *
 */
public class RegardingService extends Service{
	
	private int count=0;
	//下载相关
//	private String apkUrl="http://down1.cnmo.com/cnmo-app/a236/xiaomizb_3.8.0.apk";
	private String apkUrl;
	private static final String savePath = "/sdcard/afinal/";// 与AppUtils中的路径相同，如果集成在项目中可以调取MyApplication中路径使用
	//保存文件名
	private String saveFileName;
	private String apkName = "";
	//afinal框架
	HttpHandler<File> handler;
	FinalHttp fh = new FinalHttp();
	//自定义通知栏
	private  RemoteViews view_custom;
	private  NotificationManager notificationManager;
	private  Builder mBuilder;
	Notification notification;
	private static final int NOTIFY_ID = 0;

	private Intent Intent;
	/**
	 * 改变UI
	 */
	private Handler handler2=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Integer jinDu=(Integer) msg.obj;
				Log.e("changeNotification", jinDu+"");
				RemoteViews contentview = notification.contentView;
				contentview.setTextViewText(R.id.tv_baifenbi, jinDu
						+ "%");
				contentview.setProgressBar(R.id.pb_jindu, 100, jinDu,
						false);
				notification.defaults=0;
				notificationManager.notify(NOTIFY_ID, notification); 
				break;
			case 2:
				notificationManager.cancel(NOTIFY_ID);
				installApk();
				break;
			default:
				break;
			}
		};
	};
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		//通知栏
		Log.e("jinDu", "onStart");

		apkUrl=Intent.getStringExtra("url");

		final Intent intent2=new Intent("action_gengxin");
		intent2.putExtra("jindu", count);
		//启动广播
		initNotification();
		//下载
		downLoad();
	}
	/**
	 * 广播
	 */
	@SuppressLint("NewApi")
	private void initNotification() {
		// TODO Auto-generated method stub
		int icon = R.mipmap.icon_suyun;
		CharSequence tickerText = "开始下载";
		long when = System.currentTimeMillis();
		notification = new Notification(icon, tickerText, when);
		//设置声音
		notification.defaults=Notification.DEFAULT_SOUND;
		//优先级
		notification.priority=Notification.PRIORITY_HIGH;
		//声音只执行一次
		notification.flags=Notification.FLAG_ONLY_ALERT_ONCE;
		// 放置在"正在运行"栏目中
		notification.flags = Notification.FLAG_ONGOING_EVENT;

		RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.items_view_custom);
		// 指定个性化视图
		notification.contentView = contentView;

		notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
		notificationManager.notify(NOTIFY_ID, notification);
		
	}  
	/**
	 * 下载
	 */
	@SuppressWarnings("unchecked")
	private void downLoad() {
		// TODO Auto-generated method stub
		Log.e("123", "11111111111111111");
		int size = apkUrl.split("/").length - 1;
		saveFileName = savePath + apkUrl.split("/")[size];
		Log.e("saveFileName:", saveFileName);
		apkName = apkUrl.split("/")[size];

		handler = fh.download(apkUrl, new AjaxParams(),
				AppUtils.getMyCacheDir("") + apkName, true,
				new AjaxCallBack() {

					@Override
					public void onLoading(long count, long current) {
						// textView.setText("下载进度：" + current + "/" +
						// count);
						Log.e("123", "onLoading");
						int point = (int) ((int) current * 100 / count);
						Message message=new Message();
						message.obj=point;
						message.what=1;
						handler2.sendMessage(message);
					}
  
					@Override
					public void onSuccess(Object t) {
						if (t instanceof File) {
							File f = (File) t;
							// 自动安装
							Log.e("123", "onSuccess");
							Message message=new Message();
							handler2.sendEmptyMessage(2);
						}
					}

				});
	}
	/**
	 * 安装apk
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		getApplicationContext().startActivity(i);

	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.e("service", "onDestroy");
	}

}
